<template>
  <div class="page_tag_mgr">
    <div class="title__1">
      <el-button type="success" size="mini" plain @click.stop="goAddTag">添加标签分组</el-button>
      <el-input
        v-model="tagTable.searchName"
        size="mini"
        clearable
        style="width: 180px"
        placeholder="模糊查询标签分组名称"
        prefix-icon="el-icon-search"></el-input>
      <el-button v-if="tagTable.dataListLoading" size="mini" type="primary" disabled icon="el-icon-loading">
        搜索标签分组
      </el-button>
      <el-button v-else size="mini" type="primary" @click.stop="searchTagByName">搜索标签分组</el-button>
    </div>
    <div class="content__1">
      <el-table v-loading="tagTable.dataListLoading" :data="tagTable.dataList" border style="width: 100%">
        <el-table-column prop="groupName" label="分组名称" width="220" align="center"></el-table-column>
        <el-table-column prop="tagName" label="标签编码(唯一)" width="120" align="center"></el-table-column>
        <el-table-column prop="tag" label="标签名称" width="220" align="center"></el-table-column>
        <el-table-column prop="tagDesc" label="标签描述" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column fixed="right" align="center" width="300">
          <template slot="header">
            <span style="margin: 0 0">操作</span>
          </template>
          <template slot-scope="scope">
            <div v-if="isOpting">
              <i class="el-icon-loading"></i>
              <el-button type="info" size="mini" plain disabled>修改</el-button>
              <el-button type="warning" size="mini" plain disabled>删除标签</el-button>
              <el-button type="danger" size="mini" plain disabled>删除分组</el-button>
            </div>
            <div v-else>
              <el-button type="info" size="mini" plain @click.stop="goGroupEdit(scope.row)">修改</el-button>
              <el-button type="warning" size="mini" plain @click.stop="goTagDelete(scope.row)">删除标签</el-button>
              <el-button type="danger" size="mini" plain @click.stop="goGroupDelete(scope.row)">删除分组</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="tagTable.total > 0"
        :total="tagTable.total"
        :page.sync="tagTable.pageParam.page"
        :limit.sync="tagTable.pageParam.limit"
        @pagination="loadTagGpList"></pagination>
    </div>
    <!--添加&修改-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">
      <el-form :model="tagGroup" :rules="rules" label-width="80px">
        <el-form-item label="分组名称" prop="name">
          <el-input
            v-model="tagGroup.name"
            :maxlength="16"
            clearable
            show-word-limit
            style="width: 300px"
            :disabled="tagMgrMode.now != tagMgrMode.add"></el-input>
        </el-form-item>
      </el-form>
      <el-transfer
        v-model="tagGroup.tags"
        style="text-align: left; display: inline-block"
        filterable
        :filter-method="filterAddTags"
        filter-placeholder="搜索标签名称"
        :titles="['未选择', '已选择']"
        :button-texts="['到左边', '到右边']"
        :data="tagXingGe"></el-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button @click="hideDialog">取 消</el-button>
        <el-button v-if="dialogCommiting" type="primary" icon="el-icon-loading" disabled>确 定</el-button>
        <el-button v-else type="primary" @click="confirmTag">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
import * as tgpApi from '@/api/tags_group';
import Pagination from '@/components/Pagination';
import { MessageBox } from 'element-ui';
import { mapGetters } from 'vuex';

export default {
  name: 'TagGroup',
  components: { Pagination },
  data() {
    return {
      tagMgrMode: { now: 1, view: 1, edit: 2, add: 3 },
      tagTable: {
        // 筛选的顾客列表
        dataList: [],
        dataListLoading: false,
        total: 0,
        pageParam: { page: 1, limit: 10 },
        searchName: '',
      },
      tagGroup: {
        name: '',
        tags: [],
      },
      rules: {
        name: [
          { required: true, message: '请输入标签分组名称', trigger: 'blur' },
          { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' },
        ],
      },
      tagXingGe: [],
      dialogTitle: '添加新的标签分组',
      dialogVisible: false,
      dialogCommiting: false,
      isOpting: false,
    };
  },
  computed: {
    ...mapGetters(['name', 'id', 'deptId', 'openId']),
  },
  mounted() {
    this.loadXgTagList();
    this.loadTagGpList();
  },
  methods: {
    loadXgTagList: async function () {
      const errAlertMsg = '查询性格标签失败';
      await tgpApi
        .getXingGeTags()
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            MessageBox.alert(errAlertMsg);
            return;
          }
          const ret = res.data.data;
          if (ret && ret.length > 0) {
            for (const tag of ret) {
              this.tagXingGe.push({ key: tag.name, label: tag.tag });
            }
          }
        })
        .catch(err => {
          console.log('loadXgTagList', err);
          MessageBox.alert(errAlertMsg);
        });
    },
    loadTagGpList: async function (page, name) {
      if (this.tagTable.dataListLoading) {
        return;
      }
      this.tagTable.dataListLoading = true;
      const errAlertMsg = '查询标签分组列表失败';
      const params = {};
      params.name = !name ? null : name;
      params.pageNumber = this.tagTable.pageParam.page;
      params.pageSize = this.tagTable.pageParam.limit;
      await tgpApi
        .getPage(params)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          if (res.data.data && res.data.data.records) {
            this.tagTable.dataList = res.data.data.records;
            this.tagTable.total = res.data.data.total;
          }
        })
        .catch(e => {
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.tagTable.dataListLoading = false;
        });
    },
    searchTagByName: async function () {
      const k = this.tagTable.searchName.trim();
      await this.loadTagGpList({ page: this.tagTable.pageParam.page, limit: this.tagTable.pageParam.limit }, k);
    },
    resetDialog() {
      this.tagGroup.name = '';
      this.tagGroup.tags.splice(0, this.tagGroup.tags.length);
    },
    hideDialog: async function (row) {
      this.dialogVisible = false;
      this.resetDialog();
    },
    goAddTag: async function (row) {
      this.resetDialog();
      this.dialogTitle = '添加标签分组';
      this.tagMgrMode.now = this.tagMgrMode.add;
      this.dialogVisible = true;
    },
    goGroupEdit: async function (row) {
      if (this.isOpting) {
        return;
      }
      this.isOpting = true;
      const errAlertMsg = '查询分组包含的标签失败';
      await tgpApi
        .getGroupAllTags(row.groupName)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.tagGroup.tags.splice(0, this.tagGroup.tags.length);
          const ret = res.data.data;
          if (ret) {
            for (const tag of ret) {
              this.tagGroup.tags.push(tag.tagName);
            }
          }
          this.dialogTitle = '修改标签分组';
          this.tagGroup.name = row.groupName;
          this.tagMgrMode.now = this.tagMgrMode.edit;
          this.dialogVisible = true;
        })
        .catch(err => {
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isOpting = false;
        });
    },
    goTagDelete: async function (row) {
      if (this.isOpting) {
        return;
      }
      this.isOpting = true;
      const errAlertMsg = '删除标签失败';
      await tgpApi
        .delTag(row.id)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.loadTagGpList();
        })
        .catch(err => {
          console.log('goTagDelete', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isOpting = false;
        });
    },
    goGroupDelete: async function (row) {
      if (this.isOpting) {
        return;
      }
      this.isOpting = true;
      const errAlertMsg = '删除标签分组失败';
      await tgpApi
        .del(row.groupName)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.loadTagGpList();
        })
        .catch(err => {
          console.log('goTagDelete', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isOpting = false;
        });
    },
    confirmTag: async function () {
      if (this.dialogCommiting) {
        return;
      }
      this.dialogCommiting = true;
      const errAlertMsg = this.tagMgrMode.now == this.tagMgrMode.add ? '添加标签分组失败' : '修改标签分组失败';
      const applyFunc = this.tagMgrMode.now == this.tagMgrMode.add ? tgpApi.add : tgpApi.update;
      const params = { groupName: this.tagGroup.name, tagNames: this.tagGroup.tags };
      await applyFunc(params)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.hideDialog();
          this.loadTagGpList();
        })
        .catch(err => {
          console.log('confirmTag', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.dialogCommiting = false;
        });
    },
    filterAddTags(query, item) {
      if (!query) {
        return true;
      }
      return item.label.indexOf(query) > -1;
    },
  },
};
</script>

<style lang="scss" scoped>
$page_font_family: 思源黑体 微软雅黑 Noto Sans SC-Medium;
$title-label-size: 0.27333rem;

.page_tag_mgr {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #f8f8fa;
  padding: 5px 10px 0 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-evenly;

  .title__1 {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    gap: 20px;
  }

  .content__1 {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
  }
}
</style>
